// statistics.js - 统计分析页面所有JS逻辑

// 全局变量
let charts = {};
let currentData = {};
let isLoading = false;
let loadTimeout = null;

// 地图相关变量
let map = null;
let heatmap = null;
let markers = [];
let currentMapMode = 'heatmap'; // 'heatmap' 或 'markers'

// 页面加载时初始化

document.addEventListener('DOMContentLoaded', async function() {
    // JWT认证检查
    if (!window.AuthManager || !AuthManager.isAuthenticated()) {
        showAccessDenied();
        return;
    }
    // 检查token有效性
    try {
        await AuthManager.verifyToken();
    } catch (e) {
        showAccessDenied();
        return;
    }
    // 设置默认时间范围（最近30天）- 使用本地时间
    const now = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);
    // 转换为本地时间字符串，确保显示正确的本地时间
    const formatLocalDateTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    };
    document.getElementById('endDate').value = formatLocalDateTime(now);
    document.getElementById('startDate').value = formatLocalDateTime(startDate);
    // 初始化图表容器
    initializeChartContainers();
    // 监听标签页切换
    const geographicTab = document.getElementById('geographic-tab');
    if (geographicTab) {
        geographicTab.addEventListener('shown.bs.tab', function() {
            // 当切换到地理分布标签时，确保地图已初始化
            setTimeout(() => {
                if (!map) {
                    initMap();
                }
            }, 100);
        });
    }
    // 加载初始数据
    loadStatistics();
});

// 显示访问被拒绝
function showAccessDenied() {
    document.body.innerHTML = '<div class="access-denied" style="text-align:center;padding:50px 20px;color:#6c757d;"><i class="bi bi-shield-exclamation" style="font-size:4rem;margin-bottom:20px;"></i><h3>访问被拒绝</h3><p>请先登录系统。</p><a href="/ercms/login" class="btn btn-primary">去登录</a></div>';
}

// 初始化图表容器
function initializeChartContainers() {
    const chartContainers = document.querySelectorAll('.chart-container');
    chartContainers.forEach(container => {
        const canvas = container.querySelector('canvas');
        if (canvas) {
            // 设置画布尺寸
            canvas.style.height = '300px';
            canvas.style.width = '100%';
        }
    });
}

// 页面卸载时清理图表
window.addEventListener('beforeunload', function() {
    Object.values(charts).forEach(chart => {
        if (chart && typeof chart.destroy === 'function') {
            chart.destroy();
        }
    });
    charts = {};
});

// 加载统计数据
async function loadStatistics() {
    // 防抖处理
    if (loadTimeout) {
        clearTimeout(loadTimeout);
    }
    loadTimeout = setTimeout(async () => {
        if (isLoading) return;
        isLoading = true;
        showLoading();
        try {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            const timePeriod = document.getElementById('timePeriod').value;
            // 并行加载所有统计数据
            const [eventOverview, eventTrends, responseEfficiency, resourceUtilization, personnelPerformance, geographicDistribution] = await Promise.all([
                fetchData('/ercms/api/statistics/events/overview', { startDate, endDate }),
                fetchData('/ercms/api/statistics/events/trends', { startDate, endDate, period: timePeriod }),
                fetchData('/ercms/api/statistics/response/efficiency', { startDate, endDate }),
                fetchData('/ercms/api/statistics/resources/utilization', { startDate, endDate }),
                fetchData('/ercms/api/statistics/personnel/performance', { startDate, endDate }),
                fetchData('/ercms/api/statistics/geographic/distribution', { startDate, endDate })
            ]);
            // 存储数据
            currentData = {
                eventOverview,
                eventTrends,
                responseEfficiency,
                resourceUtilization,
                personnelPerformance,
                geographicDistribution
            };
            // 更新各个标签页
            updateOverviewTab();
            updateTrendsTab();
            updateEfficiencyTab();
            updateResourcesTab();
            updatePersonnelTab();
            updateGeographicTab();
            hideLoading();
            showMessage('数据加载成功', 'success');
        } catch (error) {
            console.error('加载统计数据失败:', error);
            hideLoading();
            showMessage('数据加载失败: ' + error.message, 'error');
        } finally {
            isLoading = false;
        }
    }, 300); // 300ms 防抖延迟
}

// 加载综合仪表盘
async function loadComprehensiveDashboard() {
    showLoading();
    try {
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;
        const data = await fetchData('/ercms/api/statistics/dashboard/comprehensive', { startDate, endDate });
        // 更新所有标签页
        currentData = data;
        updateOverviewTab();
        updateTrendsTab();
        updateEfficiencyTab();
        updateResourcesTab();
        updatePersonnelTab();
        updateGeographicTab();
        hideLoading();
        showMessage('综合仪表盘数据加载成功', 'success');
    } catch (error) {
        console.error('加载综合仪表盘失败', error);
        hideLoading();
        showMessage('综合仪表盘加载失败：' + error.message, 'error');
    }
}

// 通用数据获取函数
async function fetchData(url, params = {}) {
    const queryString = new URLSearchParams(params).toString();
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    const response = await fetch(fullUrl, {
        headers: AuthManager.getAuthHeaders()
    });
    const result = await response.json();
    if (!result.success) {
        throw new Error(result.message || '请求失败');
    }
    return result.data;
}

// 更新事件概览标签页
function updateOverviewTab() {
    const data = currentData.eventOverview;
    if (!data) return;
    // 更新概览统计卡片
    const summaryHtml = `
        <div class="summary-card">
            <h3>${data.totalEvents || 0}</h3>
            <p>总事件数</p>
        </div>
        <div class="summary-card success">
            <h3>${data.averageDailyEvents ? data.averageDailyEvents.toFixed(1) : 0}</h3>
            <p>日均事件数</p>
        </div>
        <div class="summary-card warning">
            <h3>${data.statusDistribution?.PENDING || 0}</h3>
            <p>待处理事件</p>
        </div>
        <div class="summary-card info">
            <h3>${data.statusDistribution?.RESOLVED || 0}</h3>
            <p>已解决事件</p>
        </div>
    `;
    document.getElementById('overviewSummary').innerHTML = summaryHtml;
    // 更新图表
    updateChart('eventStatusChart', 'pie', '事件状态分布', data.statusDistribution);
    updateChart('eventTypeChart', 'doughnut', '事件类型分布', data.typeDistribution);
    updateChart('eventSeverityChart', 'bar', '事件严重程度分布', data.severityDistribution);
    updateChart('eventSourceChart', 'polarArea', '事件来源分布', data.sourceDistribution);
}

// 更新趋势分析标签页
function updateTrendsTab() {
    const data = currentData.eventTrends;
    if (!data) return;
    const timeSeriesData = data.timeSeriesData || [];
    const labels = timeSeriesData.map(item => item.time);
    const counts = timeSeriesData.map(item => item.count);
    updateLineChart('eventTrendChart', '事件趋势分析', labels, counts);
}

// 更新响应效率标签页
function updateEfficiencyTab() {
    const data = currentData.responseEfficiency;
    if (!data) return;
    // 更新效率统计卡片
    const summaryHtml = `
        <div class="summary-card">
            <h3>${data.averageResponseTime ? data.averageResponseTime.toFixed(1) : 0}</h3>
            <p>平均响应时间(分钟)</p>
        </div>
        <div class="summary-card success">
            <h3>${data.responseTimeComplianceRate ? data.responseTimeComplianceRate.toFixed(1) : 0}%</h3>
            <p>响应时间达标率</p>
        </div>
        <div class="summary-card warning">
            <h3>${data.averageProcessingTime ? data.averageProcessingTime.toFixed(1) : 0}</h3>
            <p>平均处置时间(分钟)</p>
        </div>
        <div class="summary-card info">
            <h3>${data.timeDistribution?.avgTotalTime ? data.timeDistribution.avgTotalTime.toFixed(1) : 0}</h3>
            <p>平均总时间(分钟)</p>
        </div>
    `;
    document.getElementById('efficiencySummary').innerHTML = summaryHtml;
    // 更新图表
    updateChart('responseTimeChart', 'bar', '响应时间分布', data.responseTimeByType);
    updateChart('responseTimeByTypeChart', 'bar', '按事件类型的响应时间', data.responseTimeByType, true);
}

// 更新资源利用标签页
function updateResourcesTab() {
    const data = currentData.resourceUtilization;
    if (!data) return;
    // 更新资源统计卡片
    const summaryHtml = `
        <div class="summary-card">
            <h3>${data.totalResources || 0}</h3>
            <p>总资源数</p>
        </div>
        <div class="summary-card success">
            <h3>${data.utilizationRate ? data.utilizationRate.toFixed(1) : 0}%</h3>
            <p>资源利用率</p>
        </div>
        <div class="summary-card warning">
            <h3>${data.availableResources || 0}</h3>
            <p>可用资源</p>
        </div>
        <div class="summary-card info">
            <h3>${data.inUseResources || 0}</h3>
            <p>使用中资源</p>
        </div>
    `;
    document.getElementById('resourceSummary').innerHTML = summaryHtml;
    // 更新图表
    updateChart('resourceStatusChart', 'pie', '资源状态分布', data.statusDistribution);
    updateChart('resourceTypeChart', 'doughnut', '资源类型分布', data.typeDistribution);
}

// 更新人员绩效标签页
function updatePersonnelTab() {
    const data = currentData.personnelPerformance;
    if (!data) return;
    // 更新人员统计卡片
    const summaryHtml = `
        <div class="summary-card">
            <h3>${data.totalActiveUsers || 0}</h3>
            <p>总活跃人员</p>
        </div>
        <div class="summary-card success">
            <h3>${data.availabilityRate ? data.availabilityRate.toFixed(1) : 0}%</h3>
            <p>人员可用率</p>
        </div>
        <div class="summary-card warning">
            <h3>${data.busyUsers || 0}</h3>
            <p>忙碌人员</p>
        </div>
        <div class="summary-card info">
            <h3>${data.availableUsers || 0}</h3>
            <p>可用人员</p>
        </div>
    `;
    document.getElementById('personnelSummary').innerHTML = summaryHtml;
    // 更新图表
    updateChart('personnelStatusChart', 'pie', '人员状态分布', data.statusDistribution);
    updateChart('personnelRoleChart', 'doughnut', '角色分布', data.roleDistribution);
    // 人员工作量图表
    const workloadData = data.workloadStats || {};
    const workloadLabels = Object.values(workloadData).map(user => user.userName);
    const workloadValues = Object.values(workloadData).map(user => user.totalEvents);
    updateBarChart('personnelWorkloadChart', '人员工作量统计', workloadLabels, workloadValues);
}

// 更新地理分布标签页
function updateGeographicTab() {
    const data = currentData.geographicDistribution;
    if (!data) return;
    // 更新地图数据
    updateMapData(data);
    // 热点区域图表
    const hotspotData = data.hotSpots || [];
    const hotspotLabels = hotspotData.map(item => item.key);
    const hotspotValues = hotspotData.map(item => item.value);
    updateBarChart('hotspotChart', '热点区域统计', hotspotLabels, hotspotValues);
}

// 通用图表更新函数
function updateChart(canvasId, type, title, data, horizontal = false) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return;
    // 销毁现有图表
    if (charts[canvasId]) {
        charts[canvasId].destroy();
        delete charts[canvasId];
    }
    const labels = Object.keys(data || {});
    const values = Object.values(data || {});
    const colors = generateColors(labels.length);
    const options = {
        responsive: true,
        maintainAspectRatio: true,
        plugins: {
            title: {
                display: true,
                text: title
            },
            legend: {
                position: 'bottom'
            }
        }
    };
    // 如果是水平柱状图，调整配置
    if (horizontal && type === 'bar') {
        options.indexAxis = 'y';
        options.scales = {
            x: {
                beginAtZero: true
            }
        };
    }
    charts[canvasId] = new Chart(ctx, {
        type: type,
        data: {
            labels: labels,
            datasets: [{
                data: values,
                backgroundColor: colors,
                borderColor: colors,
                borderWidth: 1
            }]
        },
        options: options
    });
}

// 折线图更新函数
function updateLineChart(canvasId, title, labels, data) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return;
    if (charts[canvasId]) {
        charts[canvasId].destroy();
        delete charts[canvasId];
    }
    charts[canvasId] = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '事件数量',
                data: data,
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                title: {
                    display: true,
                    text: title
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 柱状图更新函数
function updateBarChart(canvasId, title, labels, data) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return;
    if (charts[canvasId]) {
        charts[canvasId].destroy();
        delete charts[canvasId];
    }
    charts[canvasId] = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '数量',
                data: data,
                backgroundColor: '#007bff',
                borderColor: '#0056b3',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                title: {
                    display: true,
                    text: title
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 生成颜色数组
function generateColors(count) {
    const colors = [
        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
        '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF',
        '#4BC0C0', '#FF6384', '#36A2EB', '#FFCE56'
    ];
    const result = [];
    for (let i = 0; i < count; i++) {
        result.push(colors[i % colors.length]);
    }
    return result;
}

// 显示加载状态
function showLoading() {
    const messageContainer = document.getElementById('messageContainer');
    messageContainer.innerHTML = '<div class="loading"><i class="bi bi-hourglass-split"></i> 正在加载数据...</div>';
}

// 隐藏加载状态
function hideLoading() {
    const messageContainer = document.getElementById('messageContainer');
    messageContainer.innerHTML = '';
}

// 显示消息
function showMessage(message, type) {
    const messageContainer = document.getElementById('messageContainer');
    const messageClass = type === 'error' ? 'error' : 'success';
    messageContainer.innerHTML = `<div class="${messageClass}">${message}</div>`;
    // 3秒后自动隐藏
    setTimeout(() => {
        messageContainer.innerHTML = '';
    }, 3000);
}

// 初始化地图
function initMap() {
    if (map) return; // 地图已初始化
    const mapContainer = document.getElementById('geographicMap');
    if (!mapContainer) return;
    try {
        // 创建地图实例，使用更简单的配置
        map = new AMap.Map('geographicMap', {
            zoom: 10,
            center: [116.397428, 39.90923], // 默认北京中心
            mapStyle: 'amap://styles/normal',
            viewMode: '2D'
        });
        // 暂时不添加控件，避免冲突
        // AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], function() {
        //     map.addControl(new AMap.Scale());
        //     map.addControl(new AMap.ToolBar());
        // });
        // 隐藏加载提示
        const loadingDiv = mapContainer.querySelector('.map-loading');
        if (loadingDiv) {
            loadingDiv.style.display = 'none';
        }
        console.log('地图初始化成功');
    } catch (error) {
        console.error('地图初始化失败:', error);
        const loadingDiv = mapContainer.querySelector('.map-loading');
        if (loadingDiv) {
            loadingDiv.innerHTML = `
                <i class="bi bi-exclamation-triangle" style="font-size: 3rem; color: #dc3545;"></i>
                <p>地图加载失败</p>
            `;
        }
    }
}

// 更新地图数据
function updateMapData(data) {
    if (!map) {
        initMap();
    }
    if (!map) return;
    // 清除现有数据
    clearMapData();
    console.log('地理分布数据:', data);
    if (!data || !data.coordinates || data.coordinates.length === 0) {
        console.log('没有地理数据可显示');
        return;
    }
    console.log('找到坐标数据数量:', data.coordinates.length);
    const coordinates = [];
    // 处理事件坐标
    data.coordinates.forEach((coord, index) => {
        console.log(`坐标 ${index}:`, coord);
        // 验证坐标数据
        let lng = coord.longitude;
        let lat = coord.latitude;
        // 确保坐标是数字类型
        if (typeof lng === 'string') lng = parseFloat(lng);
        if (typeof lat === 'string') lat = parseFloat(lat);
        console.log(`解析后坐标 ${index}: lng=${lng}, lat=${lat}`);
        // 验证坐标有效性
        if (lng && lat && !isNaN(lng) && !isNaN(lat) && 
            lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90) {
            coordinates.push({
                lng: lng,
                lat: lat,
                count: 1,
                eventId: coord.eventId,
                title: coord.title,
                eventType: coord.eventType,
                severity: coord.severity
            });
            console.log(`添加有效坐标: [${lng}, ${lat}]`);
        } else {
            console.log(`坐标 ${index} 无效: lng=${lng}, lat=${lat}`);
        }
    });
    console.log('有效坐标数量:', coordinates.length);
    if (coordinates.length === 0) {
        console.log('没有有效的坐标数据');
        return;
    }
    // 根据当前模式显示数据
    if (currentMapMode === 'heatmap') {
        showHeatmap(coordinates);
    } else {
        showMarkers(coordinates);
    }
    // 调整地图视野
    if (coordinates.length > 0) {
        try {
            // 使用更简单的方式设置地图视野
            const firstCoord = coordinates[0];
            map.setCenter([firstCoord.lng, firstCoord.lat]);
            map.setZoom(12);
            console.log('地图视野调整成功，中心点:', [firstCoord.lng, firstCoord.lat]);
        } catch (error) {
            console.error('地图视野调整失败:', error);
        }
    }
}

// 解析位置信息
function parseLocation(location) {
    if (!location) return null;
    // 检查是否是坐标格式 (lng,lat)
    const coordMatch = location.match(/^([\-\d.]+),([\-\d.]+)$/);
    if (coordMatch) {
        const lng = parseFloat(coordMatch[1]);
        const lat = parseFloat(coordMatch[2]);
        if (!isNaN(lng) && !isNaN(lat)) {
            return { lng, lat };
        }
    }
    return null;
}

// 显示热力图
function showHeatmap(coordinates) {
    if (!map) return;
    console.log('显示热力图，坐标数量:', coordinates.length);
    // 聚合坐标点
    const heatmapData = aggregateCoordinates(coordinates);
    console.log('聚合后的热力图数据:', heatmapData);
    // 清除现有热力图
    if (heatmap) {
        heatmap.setMap(null);
        heatmap = null;
    }
    // 使用插件方式创建热力图
    AMap.plugin(['AMap.HeatMap'], function() {
        try {
            // 创建热力图，使用简单配置
            heatmap = new AMap.HeatMap(map, {
                radius: 25,
                opacity: [0, 0.8]
            });
            const maxValue = Math.max(...heatmapData.map(item => item.count));
            console.log('热力图最大值:', maxValue);
            heatmap.setDataSet({
                data: heatmapData,
                max: maxValue
            });
            console.log('热力图创建成功');
        } catch (error) {
            console.error('热力图创建失败:', error);
        }
    });
}

// 显示标记点
function showMarkers(coordinates) {
    if (!map) return;
    console.log('显示标记点，坐标数量:', coordinates.length);
    // 清除现有标记
    if (markers.length > 0) {
        markers.forEach(marker => marker.remove());
        markers = [];
    }
    // 使用插件方式创建标记
    AMap.plugin(['AMap.Marker'], function() {
        coordinates.forEach((coord, index) => {
            try {
                const marker = new AMap.Marker({
                    position: [coord.lng, coord.lat],
                    title: coord.title || `事件 ${coord.eventId}`
                });
                marker.setMap(map);
                markers.push(marker);
                console.log(`标记点 ${index} 创建成功:`, [coord.lng, coord.lat]);
            } catch (error) {
                console.error(`标记点 ${index} 创建失败:`, error);
            }
        });
    });
}

// 聚合坐标点
function aggregateCoordinates(coordinates) {
    const aggregated = {};
    coordinates.forEach(coord => {
        const key = `${coord.lng.toFixed(4)},${coord.lat.toFixed(4)}`;
        if (aggregated[key]) {
            aggregated[key].count += coord.count;
        } else {
            aggregated[key] = {
                lng: coord.lng,
                lat: coord.lat,
                count: coord.count
            };
        }
    });
    const result = Object.values(aggregated);
    console.log('聚合结果:', result);
    return result;
}

// 清除地图数据
function clearMapData() {
    // 清除热力图
    if (heatmap) {
        heatmap.setMap(null);
        heatmap = null;
    }
    // 清除标记点
    markers.forEach(marker => {
        marker.setMap(null);
    });
    markers = [];
}

// 切换热力图模式
function toggleHeatmap() {
    currentMapMode = 'heatmap';
    document.getElementById('heatmapBtn').classList.add('active');
    document.getElementById('markersBtn').classList.remove('active');
    if (currentData.geographicDistribution) {
        updateMapData(currentData.geographicDistribution);
    }
}

// 切换标记点模式
function toggleMarkers() {
    currentMapMode = 'markers';
    document.getElementById('markersBtn').classList.add('active');
    document.getElementById('heatmapBtn').classList.remove('active');
    if (currentData.geographicDistribution) {
        updateMapData(currentData.geographicDistribution);
    }
}

// 重置地图视图
function resetMapView() {
    if (map && currentData.geographicDistribution) {
        updateMapData(currentData.geographicDistribution);
    }
}

// 获取状态文本
function getStatusText(status) {
    const statusTexts = {
        'PENDING': '待处理',
        'ASSIGNED': '已分配',
        'IN_PROGRESS': '处理中',
        'COMPLETED': '已完成',
        'RESOLVED': '已解决',
        'CLOSED': '已关闭'
    };
    return statusTexts[status] || status;
} 